using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using System.Management;
using System.Diagnostics;
using Microsoft.Build.Framework;

namespace BizTalk.BuildGenerator.Tasks
{
    /// <summary>
    /// Task to create hosts
    /// </summary>
    public class CreateHostInstance : Task
    {        
        string _Username;
        string _HostName;
        string _Password;
        string _ServerName = Environment.MachineName;        

        #region Properties        
        /// <summary>
        /// ServerName
        /// </summary>
        /// <remarks>If not supplied will default to the local machine</remarks>
        public string ServerName
        {
            get { return _ServerName; }
            set { _ServerName = value; }
        }
        /// <summary>
        /// Username
        /// </summary>
        [Required]
        public string Username
        {
            get { return _Username; }
            set { _Username = value; }
        }
        /// <summary>
        /// Password
        /// </summary>
        [Required]
        public string Password
        {
            get { return _Password; }
            set { _Password = value; }
        }
        /// <summary>
        /// HostName
        /// </summary>
        [Required]
        public string HostName
        {
            get { return _HostName; }
            set { _HostName = value; }
        }
        #endregion

        /// <summary>
        /// Execute method
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {            
            try
            {
                PutOptions options = new PutOptions();
                options.Type = PutType.CreateOnly;
                
                ManagementObject serverHostObject = HostsHelper.GetServerHostClass().CreateInstance();
                serverHostObject["ServerName"] = this._ServerName;
                serverHostObject["HostName"] = this._HostName;
                serverHostObject.InvokeMethod("Map", null);
                ManagementObject hostInstanceObject = HostsHelper.GetHostInstanceClass().CreateInstance();
                hostInstanceObject["Name"] = string.Format("Microsoft BizTalk Server {0} {1}", this._HostName, this._ServerName);
                object[] args = new object[] { this._Username, this._Password };
                hostInstanceObject.InvokeMethod("Install", args);
            }
            catch (Exception ex)
            {
                //this.Log.LogMessageFromText("", MessageImportance.High);
                Trace.WriteLine("CreateHostInstance - " + this._HostName + " - failed: " + ex.Message);
                throw;
            }
            return true;
        }
    }
}
